﻿using System.Collections.Generic;

namespace SharePhone.Query
{
    public class ExpressionFactory
    {
        public static CamlExpression CreateExpression(string fieldName, Expression.FieldType type,
                                                      Expression.Operator op, object value)
        {
            var exp = new CamlExpression(Expression.Conjunction.None);
            var qp = new QueryPart();
            qp.FieldRef = fieldName;
            qp.Operator = op;
            qp.FieldType = type;
            if (value != null)
                qp.Value = value.ToString();
            else
                qp.Value = string.Empty;
            exp.AddQueryPart(qp);
            return exp;
        }

        public static CamlExpression JoinExpression(Expression.Conjunction c, CamlExpression[] expressions)
        {
            var joinExp = new CamlExpression(c);
            if (expressions.Length > 1)
            {
                foreach (CamlExpression exp in expressions)
                {
                    if (exp == null)
                        continue;
                    if (joinExp.Joins.ContainsKey(c))
                    {
                        joinExp.Joins[c].Add(exp);
                    }
                    else
                    {
                        var exps = new List<CamlExpression>();
                        exps.Add(exp);
                        joinExp.Joins.Add(c, exps);
                    }
                }
                return joinExp;
            }
            else
            {
                if (expressions.Length == 1)
                    return expressions[0];
                else
                    return null;
            }
        }

        public static CamlExpression JoinExpression(Expression.Conjunction c, List<CamlExpression> expressions)
        {
            return JoinExpression(c, expressions.ToArray());
        }
    }
}